package JDBC;

import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 定义一个方法，将student表的数据封装为对象，然后装载到集合返回
 */
public class Query {
    public static void main(String[] args) {
        List<StudentBean> all = new Query().findAll();
        System.out.println(all);
        System.out.println(all.size());
    }

    /**
     * 查询所有student对象
     *
     * @return
     */
    public List<StudentBean> findAll() {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        StudentBean student = new StudentBean();
        List<StudentBean> list = new ArrayList<>();
        try {
            connection = JDBCUtil.openConn();
            String sql = "select * from student";
            statement = connection.createStatement();
            resultSet = statement.executeQuery(sql);

            //遍历结果集，封装对象，装载集合
            while (resultSet.next()) {
                String sno = resultSet.getString("sno");
                String sname = resultSet.getString("sname");
                String ssex = resultSet.getString("ssex");
                String sphone = resultSet.getString("sphone");
                String saddress = resultSet.getString("saddress");
                Date sbirthday = resultSet.getDate("sbirthday");
                String classno = resultSet.getString("classno");
//                String qq = resultSet.getString("QQ");

                //赋值
                student.setSno(sno);
                student.setSname(sname);
                student.setSsex(ssex);
                student.setSphone(sphone);
                student.setSaddress(saddress);
                student.setSbirthday(sbirthday);
                student.setClassno(classno);
//                student.setQq(qq);
                //装载集合
                list.add(student);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
               JDBCUtil.close(resultSet,statement,connection);
        }
        return list;
    }

}
